package com.nebula.api.modules.app.conctroller;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nebula.api.common.entity.TokenUser;
import com.nebula.api.modules.app.service.AppDemoService;
import com.nebula.api.modules.message.entity.SystemMessage;
import com.nebula.api.modules.message.service.ISysMessageService;
import com.nebula.api.utils.RedisUtils;
import com.nebula.commons.modules.form.LoginForm;
import com.nebula.commons.modules.report.service.DemoService;
import com.nebula.commons.modules.system.entity.SysUser;
import com.nebula.commons.modules.system.service.SysUserService;
import com.nebula.commons.redis.RedisKeys;
import link.ahsj.core.entitys.ApiModel;
import link.ahsj.core.utils.base.AppAssertUtil;
import link.ahsj.core.utils.str.TokenGeneratorUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Eastern unbeaten
 * @version 1.0
 * @date 2019/6/11 7:16
 * @mail chenshiyun2011@163.com
 */
@Log4j2
@RestController
@RequestMapping("/open")
public class OpenApi {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private ISysMessageService messageService;


    @GetMapping(value = "/getToken")
    public ResponseEntity<ApiModel> getToken(String username, String password) {
        AppAssertUtil.isBlank(username, "请输入帐号");
        AppAssertUtil.isBlank(password, "请输入密码");
        String token = MD5.create().digestHex("wilfcode.cn");
        //每次访问刷新一次用户吧,避免出现尴尬的失效问题
        //if (Objects.isNull(redisUtils.get(RedisKeys.getAppToken(token), TokenUser.class))) {}
        SysUser user = new SysUser();
        user.setUserId("123456");
        user.setUsername("Eastern-unbeaten");
        user.setNickName("Eastern unbeaten");
        user.setPhone("13471478474");
//        TokenUser tokenUser = new TokenUser(user);
        //保存用户到缓存里
//        redisUtils.set(RedisKeys.getAppToken(token), JSONUtil.toJsonStr(tokenUser));
        //移除旧的token并且更新
        //userTokenInfo.updateToken(token, user.getUsername());
        return ResponseEntity.ok(ApiModel.data(token));
    }

    @Autowired
    private AppDemoService appDemoService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private DemoService demoService;


    @GetMapping("/loginForm")
    public ResponseEntity<ApiModel> LoginForm() {
        LoginForm obj = new LoginForm();
        obj.setUsername("123");
        obj.setPassword("456");
        obj.setCode("789");
        return ResponseEntity.ok(ApiModel.data(obj));
    }

    @GetMapping("/message")
    public ResponseEntity<ApiModel> message() {
        Page page = new Page();
        return ResponseEntity.ok(ApiModel.data(messageService.page(page)));
    }

    @GetMapping("{id}")
    public ResponseEntity<ApiModel> getObj(@PathVariable("id") String id) {
        SystemMessage message = messageService.getById(id);
        AppAssertUtil.isNull(message, "找不到对应消息");
        return ResponseEntity.ok(ApiModel.data(message));
    }

    @PutMapping("/updates")
    public ResponseEntity<ApiModel> update(@RequestBody SystemMessage message) {
        return ResponseEntity.ok(ApiModel.data(messageService.update(messageService.lambdaUpdate()
                .eq(SystemMessage::getId, message.getId())
                .set(SystemMessage::getIsReader, SystemMessage.IS_READER_TRUE).getWrapper())));
    }

    @GetMapping(value = "/info")
    public ResponseEntity<ApiModel> info(TokenUser tokenUser) {
        return ResponseEntity.ok(ApiModel.data(sysUserService.list()));
    }

    @GetMapping("/userList")
    public ResponseEntity<ApiModel> login() {
        return ResponseEntity.ok(ApiModel.data(appDemoService.list()));
    }

    @GetMapping("/userList2")
    public ResponseEntity<ApiModel> userList2() {
        return ResponseEntity.ok(ApiModel.data(demoService.list()));
    }


    @GetMapping("/getUser")
    public ResponseEntity<ApiModel> getUser() {
        return ResponseEntity.ok(ApiModel.data(sysUserService.list()));
    }

    @GetMapping(value = "/info1")
    public ResponseEntity<ApiModel> info() {
        Map<String, Object> map = new HashMap<>();
        map.put("image", null);
        map.put("name", "李白");
        map.put("tel", "12388888888");
        map.put("age", "18");
        map.put("性别", "男");
        map.put("月薪", "十两银子");
        map.put("年薪", "120银子");
        map.put("个人简介", "是一名诗人");
        map.put("民族", "汉族");
        return ResponseEntity.ok(ApiModel.data(map));
    }

    @GetMapping("/user")
    public ResponseEntity<ApiModel> list() {
        SysUser user = new SysUser();
        user.setNickName("李白");
        user.setPhone("12388888888");
        user.setRemark("这是我的个人简介");
        return ResponseEntity.ok(ApiModel.data(user));
    }

    @GetMapping("version")
    public ResponseEntity<ApiModel> versions() {

        Map<String, Object> map = new HashMap<>();
        map.put("versions", "1.0");
        map.put("infomation", "解决多处报错,版本优化");

        return ResponseEntity.ok(ApiModel.data(map));
    }

    /**
     * 微信免登陆
     *
     * @param code
     * @return
     */
    @GetMapping("/authorization")
    public ResponseEntity<ApiModel> authorization(String code) {
        AppAssertUtil.isBlank(code, "参数不能为空");
        SysUser user = sysUserService.getOne(
                sysUserService.lambdaQuery()
                        .eq(SysUser::getUsername, code)
                        .getWrapper()
        );
//        OaUser oaUser = oaUserService.getOne(oaUserService.lambdaQuery().eq(OaUser::getAccountName,"szchenjq").getWrapper());
        AppAssertUtil.isNull(user, "用户不存在请联系管理员!");

        // 1 生成token  并且更新 token信息  abc
        String sysToken = TokenGeneratorUtils.generateValue();

        // 2 生成tokenKey  token + abc
        String tokenKey = RedisKeys.getAccessToken(sysToken);

        // 3 缓存用户信息到redis里  token+abc, userInfo
        redisUtils.setDefault(tokenKey, user);
        // 4 取出旧的token删除掉, 防止token泄露 生成出tokenKey    tokenKey+uniqueness

        String userTokenKey = RedisKeys.getAppTokenKey(user.getUsername());
        // 5 取出旧的token

        String oldkey = redisUtils.get(userTokenKey);
        if (StringUtils.isNotBlank(oldkey)) {
            // 6 生成出旧的token_key
            String oidTokenKey = RedisKeys.ACCESS_TOKEN.concat(oldkey);
            // 7 删除旧的token
            log.info("清除旧的token,key:" + oidTokenKey);
            redisUtils.delete(oidTokenKey);
        }
        // 8 使用用户唯一标识存放最新token key ,用于下次清除旧的token
        redisUtils.set(userTokenKey, sysToken);
        log.info("请求头token is : " + sysToken);
        return ResponseEntity.ok(ApiModel.data(sysToken));
    }


}
